<script setup lang="ts">
import { ref, reactive, computed, nextTick, watch } from 'vue';
import type { UnwrapRef } from 'vue';
import type { Rule } from 'ant-design-vue/es/form';
import { useRoute, useRouter } from "vue-router";
import { message } from 'ant-design-vue';
import clipboard3 from 'vue-clipboard3'
import { Dayjs } from 'dayjs';
import DayjsTimeConverter from '../../utils/dayjsTimeConverter';
const tabListNoTitle = [
  {
    key: 'timestamp',
    tab: '转换时间戳工具',
  }
];
const noTitleKey = ref('timestamp');
const { toClipboard } = clipboard3()
// 日期输入
const dateString = ref('');
// 默认时间选择
const defaultTime = ref('00:00:00');
// 转换结果
const timestamp = ref<number | null>(null);
// 错误信息
const errorMessage = ref('');

// 示例日期格式
const examples = [
  '2023-10-05',
  '2023/10/05 14:30',
  '2023.10.05 14:30:45',
  '10-05-2023',
  '2023年10月05日',
  '23-10-05',
  '10/05/2023'
];

interface FormState {
    date: string
}
const formRef = ref();
const labelCol = { span: 8 };
const wrapperCol = { span: 16 };
const formState: UnwrapRef<FormState> = reactive({
    date: '', // 开播时间
});
const rules: Record<string, Rule[]> = {
  date: [{ required: true, message: '请选择时间', trigger: 'change' }]
};

// 显示结果状态
const showResult = computed(() => timestamp.value !== null && !errorMessage.value);

// 格式化的日期（用于验证）
const formattedDate = computed(() => {
  if (timestamp.value) {
    return DayjsTimeConverter.format(timestamp.value);
  }
  return '';
});

const onTabChange = (value: string) => {
  console.log(value);
  noTitleKey.value = value;
  if(value == 'timestamp') {
  }
}

// 转换日期为时间戳
const convert = () => {
  errorMessage.value = '';
  timestamp.value = null;
  
  if (!formState.date) {
    errorMessage.value = '请输入日期时间';
    return;
  }
  
  const result = DayjsTimeConverter.toTimestamp(formState.date, {
    defaultTime: defaultTime.value,
    twoDigitYearBase: 2000,
    strict: false
  });
  
  if (result) {
    timestamp.value = result;
  } else {
    errorMessage.value = '无法解析的日期格式，请尝试其他格式';
  }
};

// 使用当前时间
const useCurrentTime = () => {
  timestamp.value = DayjsTimeConverter.now();
  formState.date = DayjsTimeConverter.format(timestamp.value);
  errorMessage.value = '';
};

// 复制到剪贴板
const copy = async (value: number) => {
//   navigator.clipboard.writeText(value.toString())
//     .then(() => {
//       alert('已复制到剪贴板');
//     })
//     .catch(err => {
//       console.error('复制失败:', err);
//       alert('复制失败，请手动复制');
//     });
  try {
    await toClipboard(value.toString());
    message.success('复制成功');
  } catch (error) {
    console.error(error);
  }
};

// 监听输入变化自动转换
watch([() => formState.date,() => defaultTime], () => {
  if (formState.date) {
    console.log('formState.date',formState.date)
    // 延迟转换，避免输入过程中频繁转换
    const timer = setTimeout(convert, 500);
    return () => clearTimeout(timer);
  }
});
</script>

<template>
     <div class="container plugin">
        <a-card
            style="width: 100%"
            :tab-list="tabListNoTitle"
            :active-tab-key="noTitleKey"
            @tabChange="key => onTabChange(key)"
        >
            <div v-if="noTitleKey === 'timestamp'">
                <div class="list-box">
                    <div class="converter-container">
                        <div class="input-section">
                            <a-form
                                ref="formRef"
                                :model="formState"
                                :rules="rules"
                                layout="inline"
                                :label-col="labelCol"
                                :wrapper-col="wrapperCol"
                            >
                                <a-form-item name="date" label="日期时间：">
                                    <a-date-picker
                                        v-model:value="formState['date']"
                                        show-time
                                        showNow
                                        placeholder="请选择时间"
                                        format="YYYY-MM-DD HH:mm:ss"
                                        value-format="YYYY-MM-DD HH:mm:ss"
                                    />
                                </a-form-item>
                                <a-form-item :wrapper-col="{ span: 24, offset: 4 }" style="text-align: right;">
                                    <a-button class="btn-ss convert-btn" type="primary" @click="convert">转换</a-button>
                                    <a-button style="margin-left: 10px" @click="useCurrentTime" class="current-btn">当前时间</a-button>
                                </a-form-item>
                            </a-form>
                            <!-- <label for="dateInput">日期时间：</label>
                            <input
                                type="text"
                                id="dateInput"
                                v-model="dateString"
                                placeholder="请输入日期时间，如 2023-10-05 14:30"
                                @keyup.enter="convert"
                            />
                            
                            <button @click="convert" class="convert-btn">转换</button>
                            <button @click="useCurrentTime" class="current-btn">当前时间</button> -->
                        </div>
                        
                        <div class="result-section" v-if="showResult">
                            <h3>转换结果</h3>
                            <!-- <div class="result-item">
                                <span class="label">毫秒时间戳：</span>
                                <span class="value">{{ timestamp }}</span>
                                <button @click="copy(timestamp)" class="copy-btn">复制</button>
                            </div> -->
                            <div class="result-item">
                                <span class="label">时间戳：</span>
                                <span class="value">{{ Math.floor(timestamp / 1000) }}</span>
                                <button @click="copy(Math.floor(timestamp / 1000))" class="copy-btn">复制</button>
                            </div>
                            <div class="result-item">
                                <span class="label">格式化验证：</span>
                                <span class="value">{{ formattedDate }}</span>
                            </div>
                        </div>
                        
                        <div class="error-message" v-if="errorMessage">
                            ⚠️ {{ errorMessage }}
                        </div>
                        
                    </div>
                </div>
            </div>
        </a-card>
     </div>
</template>

<style scoped>

.converter-container {
  padding: 1rem;
}

.input-section {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  margin-bottom: 2rem;
  align-items: center;
}

#dateInput {
  flex: 1;
  min-width: 250px;
  padding: 0.8rem 1rem;
  border: 1px solid #cbd5e1;
  border-radius: 6px;
  font-size: 1rem;
  transition: border-color 0.2s;
}

#dateInput:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

select {
  padding: 0.8rem 1rem;
  border: 1px solid #cbd5e1;
  border-radius: 6px;
  background-color: #fff;
  font-size: 1rem;
  cursor: pointer;
}

.result-section {
  padding: 1.5rem;
  background-color: #f8fafc;
  border-radius: 6px;
  margin-bottom: 2rem;
}

.result-item {
  margin: 1rem 0;
  padding: 0.8rem 0;
  border-bottom: 1px solid #e2e8f0;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.result-item:last-child {
  border-bottom: none;
}

.label {
  font-weight: 600;
  color: #475569;
  min-width: 140px;
}

.value {
  flex: 1;
  color: #1e293b;
  word-break: break-all;
  margin-right: 1rem;
}

.copy-btn {
  padding: 0.3rem 0.8rem;
  background-color: #e2e8f0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.8rem;
  transition: background-color 0.2s;
}

.copy-btn:hover {
  background-color: #cbd5e1;
}

.error-message {
  color: #dc2626;
  padding: 1rem;
  background-color: #fee2e2;
  border-radius: 6px;
  margin-bottom: 2rem;
  border: 1px solid #fecaca;
}

.examples-section {
  margin-top: 2rem;
}

.examples-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 0.8rem;
}

.example-item {
  padding: 0.8rem;
  background-color: #f1f5f9;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 0.9rem;
  text-align: center;
}

.example-item:hover {
  background-color: #e2e8f0;
  transform: translateY(-2px);
}

@media (max-width: 768px) {
  .dayjs-converter-demo {
    padding: 1rem;
    margin: 1rem;
  }
  
  .input-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .convert-btn, .current-btn {
    width: 100%;
  }
}
</style>